from flask import request
from flask_restful import Resource
from database import Database




class Register(Resource):
    def post(self):
        db = Database()
        cursor = db.get_connection().cursor()
        data = request.get_json()
        username = data.get('username')
        password = data.get('password')
        first_name = data.get('firstName')
        last_name = data.get('lastName')
        email = data.get('email')
        address = data.get('address')
        user_type = data.get('type')  # Changed variable name from type1 to user_type for clarity

        if is_valid_username(username) and is_valid_password(password) and is_valid_email(email) and is_valid_address(
                address) and is_valid_user_type(user_type):

            cursor.execute("SELECT * FROM useraccount WHERE userId = %s", (username,))
            user = cursor.fetchone()
            if user is None:
                db.execute_query(
                    "INSERT INTO useraccount (userId, type, borrowLimit, password, firstName, lastName, email, "
                    "address) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)",
                    (username, user_type, 6, password, first_name, last_name, email, address))

                # Commit the transaction

                return {"message": "User created successfully"}, 200
            else:
                return {"message": "User already exists"}, 409  # Changed return status to 409 Conflict
        else:

            return {"message": "One or more parameters are incorrect"}, 409


def is_valid_username(username):
    # Check if username is not empty and contains only alphanumeric characters
    return username and username.isalnum()


def is_valid_password(password):
    # Check if password is not empty and has a minimum length requirement
    return password and len(password) >= 8


def is_valid_name(name):
    # Check if name is not empty and contains only letters
    return name and name.isalpha()


def is_valid_email(email):
    # Check if email is not empty and matches a basic email pattern
    if email:
        import re
        email_pattern = r'^[\w\.-]+@[\w\.-]+\.\w+$'
        return re.match(email_pattern, email.strip())
    return False


def is_valid_address(address):
    # Check if address is not empty
    return bool(address)


def is_valid_image_url(image_url):
    # Check if image_url is not empty
    return bool(image_url)


def is_valid_user_type(user_type):
    # Check if user_type is either 'student' or 'teacher'
    return user_type in ['student', 'teacher']
